package com.linkage.jz.bankruptcy.fragment.Vote;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteResultImageActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteVotersDetailActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteRate;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.BundleUtils;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.ScreenUtils;
import com.linkage.jz.bankruptcy.widget.pieView.PieData;
import com.linkage.jz.bankruptcy.widget.pieView.PieView;
import com.linkage.seapeak.utils.CommonUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 债权人表决详情页Tab之表决进度
 */
public class ProVoteDetailRateFragment extends ProVoteBaseFragment implements View.OnClickListener {

    public static final String ARG_PARAM = "arg_param";
    private ProVote proVote;
    private View rootView;
    private TextView textStatus;
    private TextView textNotStart;//还没开始
    private Button btnVoteSendFile;//查看表决结果文件

    private ViewPager mViewPager;
    private LinearLayout mLinearLayout;
    //View动态数组
    private List<View> mViewList = new ArrayList<View>();
    private List<ImageView> mDots;
    private MyAdapter mAdapter;

    public static ProVoteDetailRateFragment newInstance() {
        ProVoteDetailRateFragment fragment = new ProVoteDetailRateFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        proVote = BundleUtils.getProVote();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_pro_vote_detai_rate, container, false);
        }
        textStatus = rootView.findViewById(R.id.vote_rate_state);
        textNotStart = rootView.findViewById(R.id.vote_rate_state_tip);
        btnVoteSendFile = rootView.findViewById(R.id.btn_vote_send_file);
        mViewPager = rootView.findViewById(R.id.vote_rate_viewpager);
        mLinearLayout = rootView.findViewById(R.id.vote_rate_linear);
        mAdapter = new MyAdapter();
        mViewPager.setAdapter(mAdapter);
        mViewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        bindStatus(proVote);
        fetchData();
        //pieView = rootView.findViewById(R.id.pieView);
        //pieView.setData(pieDataList);
        if(proVote.getResultId() != null && proVote.getResultStatus() == 1) {
            btnVoteSendFile.setVisibility(View.VISIBLE);
        }else {
            btnVoteSendFile.setVisibility(View.GONE);
        }
        btnVoteSendFile.setOnClickListener(this);
        return rootView;
    }

    /**
     * 获取详情
     */
    private void fetchData() {
        showLoading();
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .getVoteSchedule_Creditor(userToken, proVote.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        JsonObject data = json.getAsJsonObject("data");
                        List<ProVoteRate> list = ProVoteRate.parse(data);
                        addPage(list);
                    }

                    @Override
                    public void onCompleted() {
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }
                });
    }

    private void addPage(List<ProVoteRate> data) {
        bindStatus(proVote);
        LayoutInflater inflater = getLayoutInflater();
        if(data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                ProVoteRate proVoteRate = data.get(i);
                View view = inflater.inflate(R.layout.pro_vote_view_vote_rate, null);
                TextView groupNameText = view.findViewById(R.id.item_name);
                if(!TextUtils.isEmpty(proVoteRate.getGroupName())) {
                    groupNameText.setText(proVoteRate.getGroupName());
                }
                initCircleData(view, proVoteRate);
                TextView goto_detail = view.findViewById(R.id.goto_detail);
                if(i == 0) {//只显示第一个“查看表决明细”
//                    goto_detail.setVisibility(View.VISIBLE);
//                    if (proVoteRate.isDefaultAgreed()) {
                    if("1".equalsIgnoreCase(proVote.getAuth().isViewVotingDetails())||"true".equalsIgnoreCase(proVote.getAuth().isViewVotingDetails())) {
                        goto_detail.setVisibility(View.VISIBLE);
                    }else{
                        goto_detail.setVisibility(View.INVISIBLE);
                    }
                        goto_detail.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ProVoteVotersDetailActivity.showVoters(getActivity(), proVoteRate.getGroupId());
                            }
                        });
//                    } else {
//                        goto_detail.setVisibility(View.GONE);
//                    }
                }else {
                    goto_detail.setVisibility(View.GONE);
                }
                mViewList.add(view);
            }
        }
        addIndicator();
        mAdapter.notifyDataSetChanged();
    }

    private void bindStatus(ProVote proVote) {
        int statusColor = getResources().getColor(R.color.pro_vote_status_jxz);
        String statusText = "";
        switch (proVote.getStatus()) {
            case 0:
                statusColor = getResources().getColor(R.color.pro_vote_status_wfc);
                statusText = "未发出";
                textNotStart.setVisibility(View.VISIBLE);
                break;
            case 1://未开始
                statusColor = getResources().getColor(R.color.pro_vote_status_wks);
                statusText = "未开始";
                textNotStart.setVisibility(View.GONE);
                break;
            case 2://进行中
                statusColor = getResources().getColor(R.color.pro_vote_status_jxz);
                statusText = "进行中";
                textNotStart.setVisibility(View.GONE);
                break;
            case 3://已结束的
                statusColor = getResources().getColor(R.color.pro_vote_status_yjs);

//                if(proVote.getResultStatus()==0)
//                {
//                    statusText = "已结束(未发布)";
//                }else {
                    statusText = "已结束";
//                }
                textNotStart.setVisibility(View.GONE);
                break;
            case 4:
                statusColor = getResources().getColor(R.color.pro_vote_status_ycx);
                statusText = "已撤销";
                textNotStart.setVisibility(View.GONE);
                break;
            case 5:
                statusColor = getResources().getColor(R.color.pro_vote_status_ytg);
//                if(proVote.getResultStatus()==0)
//                {
//                    statusText = "已通过(未发布)";
//                }else {
                    statusText = "已通过";
//                }
                textNotStart.setVisibility(View.GONE);
                break;
            case 6:
                statusColor = getResources().getColor(R.color.pro_vote_status_wtg);
//                if(proVote.getResultStatus()==0)
//                {
//                    statusText = "未通过(未发布)";
//                }else {
//                    statusText = "未通过";
//                }
                statusText = "未通过";
                textNotStart.setVisibility(View.GONE);
                break;
            case 7:
                statusColor = getResources().getColor(R.color.pro_vote_status_ysc);
                statusText = "已删除";
                textNotStart.setVisibility(View.GONE);
                break;
        }
        textStatus.setText(statusText);
        textStatus.setTextColor(statusColor);
    }

    private void initCircleData(View view, ProVoteRate proVoteRate) {
        BigDecimal b100 = new BigDecimal(Double.toString(100));
        //设置第一个饼状图数据
        PieView pieView1 = view.findViewById(R.id.pieView1);
        ArrayList<PieData> pieDataList1 = new ArrayList<>();


        PieData pieData11 = new PieData("同意", proVoteRate.getAgreedVoterRate());
        PieData pieData12 = new PieData("不同意", proVoteRate.getDisAgreedVoterRate());
//        PieData pieData13 = new PieData("未参会", proVoteRate.getNotAtdVoterRate());
        PieData pieData14 = new PieData("参会未表决", proVoteRate.getNoVoteRate());
        pieData11.setColor(getResources().getColor(R.color.pro_vote_color_agree));
        pieData12.setColor(getResources().getColor(R.color.pro_vote_color_not_agree));
//        pieData13.setColor(getResources().getColor(R.color.pro_vote_color_not_join));
        pieData14.setColor(getResources().getColor(R.color.pro_vote_color_not_vote));
        pieDataList1.add(pieData11);
        pieDataList1.add(pieData12);
//        pieDataList1.add(pieData13);
        pieDataList1.add(pieData14);
        pieView1.setData(pieDataList1);
        //第一个图下面的文字
        TextView text_total_num = view.findViewById(R.id.text_total_num);
        TextView pro_vote_agree_number = view.findViewById(R.id.pro_vote_agree_number);
        TextView pro_vote_agree_percent = view.findViewById(R.id.pro_vote_agree_percent);
        TextView pro_vote_not_agree_number = view.findViewById(R.id.pro_vote_not_agree_number);
        TextView pro_vote_not_agree_percent = view.findViewById(R.id.pro_vote_not_agree_percent);
        TextView pro_vote_not_join_number = view.findViewById(R.id.pro_vote_not_join_number);
        TextView pro_vote_not_join_percent = view.findViewById(R.id.pro_vote_not_join_percent);
        TextView pro_vote_not_vote_number = view.findViewById(R.id.pro_vote_not_vote_number);
        TextView pro_vote_not_vote_percent = view.findViewById(R.id.pro_vote_not_vote_percent);
        text_total_num.setText(proVoteRate.getTotalMeetingMember()+"人");
        pro_vote_agree_number.setText(proVoteRate.getAgreedNum()+"人");
        BigDecimal a11 = new BigDecimal(Double.toString(proVoteRate.getAgreedVoterRate()));
        pro_vote_agree_percent.setText("占比" + a11.multiply(b100).doubleValue() +"%");
        pro_vote_not_agree_number.setText(proVoteRate.getDisAgreedNum()+"人");
        BigDecimal a12 = new BigDecimal(Double.toString(proVoteRate.getDisAgreedVoterRate()));
        pro_vote_not_agree_percent.setText("占比" + a12.multiply(b100).doubleValue() +"%");
        pro_vote_not_join_number.setText(proVoteRate.getNotAttendNum()+"人");
        BigDecimal a13 = new BigDecimal(Double.toString(proVoteRate.getNotAtdVoterRate()));
        pro_vote_not_join_percent.setText("占比" + a13.multiply(b100).doubleValue() +"%");
        pro_vote_not_join_number.setVisibility(View.GONE);
        pro_vote_not_join_percent.setVisibility(View.GONE);
        //未表决人数
        LinearLayout layout_pro_vote_not_vote_color = view.findViewById(R.id.pro_vote_not_vote_layout);
        if(proVoteRate.isDefaultAgreed()) {
            layout_pro_vote_not_vote_color.setVisibility(View.GONE);
        }else {
            layout_pro_vote_not_vote_color.setVisibility(View.VISIBLE);
            pro_vote_not_vote_number.setText(proVoteRate.getNoVoteNum()+"人");
            BigDecimal a14 = new BigDecimal(Double.toString(proVoteRate.getNoVoteRate()));
            pro_vote_not_vote_percent.setText("占比" + a14.multiply(b100).doubleValue() +"%");
        }

        //设置第二个饼状图数据
        PieView pieView2 = view.findViewById(R.id.pieView2);
        ArrayList<PieData> pieDataList2 = new ArrayList<>();


        double tmp = proVoteRate.getAgreedAmount()/proVoteRate.getTotalAmount();
        PieData pieData21 = new PieData("同意", tmp);
         tmp = proVoteRate.getDisAgreedAmount()/proVoteRate.getTotalAmount();
        PieData pieData22 = new PieData("不同意", tmp);
        tmp = proVoteRate.getNotAttendAmount()/proVoteRate.getTotalAmount();
        PieData pieData23 = new PieData("未参会", tmp);
        tmp = proVoteRate.getNoVoteAmount()/proVoteRate.getTotalAmount();
        PieData pieData24 = new PieData("参会未表决", tmp);
        pieData21.setColor(getResources().getColor(R.color.pro_vote_color_agree));
        pieData22.setColor(getResources().getColor(R.color.pro_vote_color_not_agree));
        pieData23.setColor(getResources().getColor(R.color.pro_vote_color_not_join));
        pieData24.setColor(getResources().getColor(R.color.pro_vote_color_not_vote));
        pieDataList2.add(pieData21);
        pieDataList2.add(pieData22);
        pieDataList2.add(pieData23);
        pieDataList2.add(pieData24);
        pieView2.setData(pieDataList2);
        //第二个图下面的文字
        TextView text_total_money = view.findViewById(R.id.text_total_money);
        TextView pro_vote_money_agree_number = view.findViewById(R.id.pro_vote_money_agree_number);
        TextView pro_vote_money_agree_percent = view.findViewById(R.id.pro_vote_money_agree_percent);
        TextView pro_vote_money_not_agree_number = view.findViewById(R.id.pro_vote_money_not_agree_number);
        TextView pro_vote_money_not_agree_percent = view.findViewById(R.id.pro_vote_money_not_agree_percent);
        TextView pro_vote_money_not_join_number = view.findViewById(R.id.pro_vote_money_not_join_number);
        TextView pro_vote_money_not_join_percent = view.findViewById(R.id.pro_vote_money_not_join_percent);
        TextView pro_vote_money_not_vote_number = view.findViewById(R.id.pro_vote_money_not_vote_number);
        TextView pro_vote_money_not_vote_percent = view.findViewById(R.id.pro_vote_money_not_vote_percent);
        DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.



        text_total_money.setText(CommonUtils.resetMoney(proVoteRate.getTotalAmount())+"元");
//        pro_vote_money_agree_number.setText(decimalFormat.format(proVoteRate.getAgreedAmount())+"元");
        pro_vote_money_agree_number.setText(CommonUtils.resetMoney(proVoteRate.getAgreedAmount())+"元");
        BigDecimal a21 = new BigDecimal(Double.toString(proVoteRate.getAgreedMoneyRate()));
        pro_vote_money_agree_percent.setText("占比" + a21.multiply(b100).doubleValue() +"%");
//        pro_vote_money_not_agree_number.setText(decimalFormat.format(proVoteRate.getDisAgreedAmount())+"元");
        pro_vote_money_not_agree_number.setText(CommonUtils.resetMoney(proVoteRate.getDisAgreedAmount())+"元");
        BigDecimal a22 = new BigDecimal(Double.toString(proVoteRate.getDisAgreedMoneyRate()));
        pro_vote_money_not_agree_percent.setText("占比" + a22.multiply(b100).doubleValue() +"%");
//        pro_vote_money_not_join_number.setText(decimalFormat.format(proVoteRate.getNotAttendAmount())+"元");
        pro_vote_money_not_join_number.setText(CommonUtils.resetMoney(proVoteRate.getNotAttendAmount())+"元");
        BigDecimal a23 = new BigDecimal(Double.toString(proVoteRate.getNotAtdMoneyRate()));
        pro_vote_money_not_join_percent.setText("占比" + a23.multiply(b100).doubleValue() +"%");
        //未表决金额
        LinearLayout layout_pro_vote_money_not_vote_color = view.findViewById(R.id.pro_vote_money_not_vote_layout);
        if(proVoteRate.isDefaultAgreed()) {
            layout_pro_vote_money_not_vote_color.setVisibility(View.GONE);
        }else {
            layout_pro_vote_money_not_vote_color.setVisibility(View.VISIBLE);
//            pro_vote_money_not_vote_number.setText(decimalFormat.format(proVoteRate.getNoVoteAmount())+"元");
            pro_vote_money_not_vote_number.setText(CommonUtils.resetMoney(proVoteRate.getNoVoteAmount())+"元");
            BigDecimal a24 = new BigDecimal(Double.toString(proVoteRate.getNoVoteMoneyRate()));
            pro_vote_money_not_vote_percent.setText("占比" + a24.multiply(b100).doubleValue() +"%");
        }
    }

    private void addIndicator() {
        mDots = new ArrayList<ImageView>();
        for (int i = 0; i < mViewList.size(); i++) {
            ImageView imageView = new ImageView(getActivity());
            int width = ScreenUtils.dip2px(getActivity(), 8);
            int height = ScreenUtils.dip2px(getActivity(), 8);
            int margin = ScreenUtils.dip2px(getActivity(), 5);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
            params.setMargins(margin, margin, margin, margin);//设置margin,也就是外边距。
            imageView.setLayoutParams(params);//传入参数params设置宽和高
            imageView.setImageResource(R.drawable.pro_vote_viewpager_indicate_not_choose);//设置图片
            mLinearLayout.addView(imageView);//将图片添加到布局中
            //将dot添加到dots集合中
            mDots.add(imageView);
        }
        mDots.get(0).setImageResource(R.drawable.pro_vote_viewpager_indicate_choose);//设置启动后显示的第一个点
    }

    class MyAdapter extends PagerAdapter {
        //大小
        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //获取图片view
            View view = mViewList.get(position);
            //设置到容器,也就是ViewPager
            container.addView(view);
            //返回控件
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //从容器中删除
            container.removeView(mViewList.get(position));
        }
    }

    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            for (ImageView imageView : mDots) {
                imageView.setImageResource(R.drawable.pro_vote_viewpager_indicate_not_choose);
            }
            //设置当前显示的页面的dot设置为dot_focused
            mDots.get(position).setImageResource(R.drawable.pro_vote_viewpager_indicate_choose);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    /**
     * 获取详情
     */
    private void fetchVoteResult() {
        showLoading();
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .getVoteResultFile(userToken, proVote.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        String fileUrl = json.getAsJsonObject("data").get("fileUrl").getAsString();
                        if(!TextUtils.isEmpty(fileUrl)) {
                            ArrayList<String> urlList = new ArrayList<>();
                            urlList.add(fileUrl);
                            ProVoteResultImageActivity.start(getActivity(), urlList, 0, 0);
                        }
                    }

                    @Override
                    public void onCompleted() {
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_vote_send_file:
                fetchVoteResult();
                break;
        }
    }
}
